<template>
  <f7-page>
    <f7-navbar>
      <f7-nav-left>
        <f7-link icon-material="arrow_back" @click="comeBack"></f7-link>
      </f7-nav-left>
      <f7-nav-title>二维码扫描</f7-nav-title>
      <f7-nav-right>
        <!-- <f7-link
          style="color: white"
          @click="$refs.actionsOneGroup.f7Actions.open()"
          >相册</f7-link
        > -->
      </f7-nav-right>
    </f7-navbar>
    <div class="scan">
      <div id="bcid" v-if="isMobile">
        <div style="height: 40%"></div>
        <p class="tip">正在扫描</p>
      </div>

      <qrcode-stream v-if="isWeb" @decode="onDecode"></qrcode-stream>
    </div>
    <f7-actions ref="actionsOneGroup">
      <f7-actions-group>
        <f7-actions-button @click="scanImg">从相册选取二维码</f7-actions-button>
      </f7-actions-group>
    </f7-actions>
  </f7-page>
</template>

<script>
import controller from "@/libs/framework/controller";
import Config from "@/libs//config";
import _ from "lodash";

import { QrcodeStream, QrcodeDropZone, QrcodeCapture } from "vue-qrcode-reader";

export default class List extends controller {
  mixin() {
    return {
      components: {
        QrcodeStream,
        QrcodeDropZone,
        QrcodeCapture,
      },
      data() {
        return {
          isMobile: true,
          isWeb: false,
          scanResult: "",
        };
      },
      mounted() {
        if (window.qmplus.isMobile()) {
          this.isMobile = true;
          this.isWeb = false;
          //跳转时自动开启
          this.startRecognize();
        } else if (window.qmplus.isWeb()) {
          this.isMobile = false;
          this.isWeb = true;
        }
      },
      methods: {
        onDecode(decodedString) {
          this.$f7.dialog.alert(decodedString);
        },
        // 创建扫描控件
        startRecognize() {
          let that = this;
          if (!window.plus) return;
          window.scan = new plus.barcode.Barcode(
            "bcid",
            [plus.barcode.QR, plus.barcode.EAN8, plus.barcode.EAN13],
            {
              frameColor: "#009DE2",
              scanbarColor: "#009DE2",
            }
          );

          function onmarked(type, result, file) {
            switch (type) {
              case plus.barcode.QR:
                type = "QR";
                break;
              case plus.barcode.EAN13:
                type = "EAN13";
                break;
              case plus.barcode.EAN8:
                type = "EAN8";
                break;
              default:
                type = "其它" + type;
                break;
            }
            result = result.replace(/\n/g, "");
            that.scanResult = result;
            window.localStorage.setItem("scanResult", result);
            // window.localStorage.scanResult = result;
            if (that.$f7route.query.way) {
              that.appendToFiles(file, result);
            } else {
              that.closeScan(result);
            }
          }
          scan.onmarked = onmarked;
          // 开始扫描
          scan.start({
            conserve: true,
            filename: "_doc/barcode/",
          });
        },
        //上传二维码
        appendToFiles(path, result) {
          var that = this;
          window.plus.io.resolveLocalFileSystemURL(
            path,
            (entry) => {
              entry.file(async (file) => {
                const img = await this.createImg(file);
                const canvas = document.createElement("canvas");
                const ctx = canvas.getContext("2d");
                canvas.width = img.width;
                canvas.height = img.height;
                // 将图片画到画布上
                ctx.drawImage(img, 0, 0);
                let base64img = canvas.toDataURL();
                that.sendImg(result, base64img);
                img.remove();
                canvas.remove();
              });
            },
            (e) => {
              console.error("appendToFiles error", e);
            }
          );
        },
        createImg(file) {
          const img = document.createElement("img");
          const reader = window.plus
            ? new plus.io.FileReader()
            : new FileReader();
          reader.readAsDataURL(file);
          return new Promise((resolve) => {
            reader.onloadend = (e) => {
              img.src = e.target.result;
              img.addEventListener("load", () => {
                resolve(img);
              });
            };
          });
        },
        //绑定图片与信息
        sendImg(result, base64img) {
          var self = this;
          var base64img = base64img.replace("data:image/png;base64,", "");
          var url = "";
          if (self.$f7route.query.way == 1) {
            url = "/quality/concreteWitness/bindQrCodeWitness";
          } else {
            url = "/quality/materialWitness/bindQrCodeWitness";
            base64img = "";
          }
          self.$f7.request.post(
            url,
            {
              qrcodeImg: base64img,
              witnessId: self.$f7route.query.witnessId,
              digtCode: result,
            },
            (r) => {
              r = JSON.parse(r);
              if (r && r.success) {
                self.$framework.$f7.dialog.toast("二维码扫描成功");
              } else {
                self.$framework.$f7.dialog.toast(r.message || "二维码扫描失败");
              }
              self.closeScan(result);
            },
            (e) => {
              this.$framework.$f7.dialog.toast("二维码扫描失败");
              self.closeScan(result);
            }
          );
        },
        // 关闭返回
        closeScan(result) {
          if (window.scan) {
            window.scan.close();
          }
          this.$f7.views.current.router.back({ animate: false });
        },
        comeBack() {
          if (window.scan) {
            window.scan.close();
          }
          this.$f7.views.current.router.back({ animate: false });
        },
        scanImg() {
          // 从系统相册选择文件
          if (!window.plus) return;
          plus.gallery.pick(
            function (path) {
              plus.barcode.scan(
                path,
                function (type, result) {
                  window.localStorage.scanResult2 = result;
                },
                function (e) {
                  window.localStorage.scanResult2 = e;
                  plus.nativeUI.alert("如果图片无法识别,请用扫码上传");
                }
              );
            },
            { filter: "image" }
          );
        },
      },
    };
  }
}
</script>
<style scoped>
.scan {
  height: 100%;
}

#bcid {
  width: 100%;
  height: auto;
  position: absolute;
  left: 0;
  right: 0;
  top: 56px;
  bottom: 73px;
  text-align: center;
  color: #fff;
  background: black;
  padding-bottom: 15px;
  box-sizing: border-box;
}

@media screen and (max-height: 812px) {
  #bcid {
    top: calc(56px + env(safe-area-inset-top));
    bottom: calc(73px + env(safe-area-inset-bottom));
  }
}

@media screen and (min-height: 800px) {
  #bcid {
    --safe-area-inset-bottom: env(safe-area-inset-bottom);
    bottom: calc(73px + var(--safe-area-inset-bottom));
  }
}

header {
  position: absolute;
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  color: #009de2;
  left: 0.3rem;
  top: 0;
  right: 0.3rem;
  height: 1rem;
  line-height: 1rem;
  z-index: 2;
}

.page >>> .page-content {
  background-color: black;
}
</style>
